<template>
  <div>
    <!--卡片-->
    <el-row :gutter="24">
      <el-col v-for="item in list.cartLists" v-bind="grid2">
        <cart-list style="cursor: pointer;margin-bottom: 10px" :obj="item" />
      </el-col>
    </el-row>
    <!--订单-->
    <div class="container mt10">
      <el-form size="small" label-width="72px">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="订单状态：">
              <el-radio-group v-model="tabStatus" size="small" @change="onStatus">
                <el-radio-button v-for="item in list.statusData" :key="item.key" :label="item.key">{{ item.label }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="支付方式：">
              <el-radio-group v-model="tabMode" size="small" @change="onPaymentMethod">
                <el-radio-button v-for="item in list.modeData" :key="item.key" :label="item.key">{{ item.label }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-col v-bind="grid" style="padding-left: 0;padding-right: 0">
              <el-form-item label="搜索：">
                <el-input v-model="tabKeywords" placeholder="请输入" size="small" class="search-select" clearable>
                  <template v-slot:append>
                    <el-button icon="el-icon-search" size="small" @click="onSeachKeywordList" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <!--<el-form-item label="创建时间：">
          <el-date-picker
            v-model="tabDateLimit"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            size="small"
            type="daterange"
            placement="bottom-end"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="createDate"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item label="搜索：" prop="keywords">
          <el-input v-model="tabKeywords" class="seachKeywords" placeholder="请输入" clearable>
            <el-select slot="prepend" v-model="tabFieldKey" class="select_field_key">
              <el-option label="全部" value="all" />
              <el-option label="订单号" value="orderNumber" />
              <el-option label="UID" value="uid" />
              <el-option label="用户姓名" value="userName" />
              <el-option label="用户电话" value="userPhone" />
              <el-option label="订单中商品件数" value="piece" />
              <el-option label="商品名称(模糊)" value="tradeName" />
            </el-select>
            <el-button slot="append" icon="el-icon-search" />
          </el-input>
        </el-form-item>-->
      </el-form>
    </div>
    <el-row>
      <el-col :span="24">
        <el-col :xs="24" :sm="24" :md="16" :lg="12" :xl="12">
          <el-dropdown class="ml10 mr10" :hide-on-click="false">
            <el-button size="small" plain>
              导出发货单<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="onInvoiceExports">导出发货单</el-dropdown-item>
              <el-dropdown-item @click.native="onExports">导出订单</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
        <el-col :xs="24" :sm="24" :md="8" :lg="12" :xl="12" style="text-align: right;">
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import cartList from './cart'
import { NumFormat } from '@/filters/commFilter'
import { getOrderList } from '@/api/order'
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  name: 'OrderListDetailsHeader',
  components: {
    cartList
  },
  props: {
    tabList: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      grid: {
        xl: 5,
        lg: 7,
        md: 12,
        sm: 12,
        xs: 24
      },
      grid2: {
        xl: 6,
        lg: 6,
        md: 12,
        sm: 12,
        xs: 24
      },
      list: {
        statusData: [],
        cartLists: [],
        modeData: [
          { key: -1, label: '全部' },
          { key: 0, label: '微信支付' },
          { key: 1, label: '支付宝支付' }/*,
          { key: 'last7Days', label: '余额支付' },
          { key: 'last30Days', label: '线下支付' }*/
        ]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()))
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.setTime(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - 1)))
              end.setTime(end.setTime(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())))
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近7天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近30天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '本月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.setTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1)))
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '本年',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.setTime(new Date(new Date().getFullYear(), 0, 1)))
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  computed: {
    ...mapGetters({
      totalCount: 'orderTotalCount'
    }),
    ...mapState({
      status: state => state.order.tableFrom.status,
      mode: state => state.order.tableFrom.mode,
      dateLimit: state => state.order.tableFrom.dateLimit,
      keywords: state => state.order.tableFrom.keywords,
      selectionDate: state => state.order.selectionDate
    }),
    tabStatus: {
      get() {
        return this.status
      },
      set(newVal) {
        if (newVal < 9) {
          console.log(newVal)
          this.tableFromStatus(newVal)
          this.tableFromIsDel(0)
        } else if (newVal >= 9) {
          this.tableFromIsDel(1)
          this.tableFromStatus(9)
        }
      }
    },
    tabMode: {
      get() {
        return this.mode
      },
      set(newVal) {
        this.tableFromMode(newVal)
      }
    },
    tabDateLimit: {
      get() {
        return this.dateLimit
      },
      set(newVal) {
        this.tableFromDateLimit(newVal)
      }
    },
    tabKeywords: {
      get() {
        return this.keywords
      },
      set(newVal) {
        this.tableFromKeywords(newVal)
      }
    }
  },
  watch: {
    tabList(val, oldVal) {
      this.$set(this.list, 'statusData', [
        { key: -1, label: `全部 ${this.tabList['type_All_Count'] || 0}` },
        { key: 1, label: `待支付 ${this.tabList['processing_Count'] || 0}` },
        { key: 2, label: `已取消 ${this.tabList['declined_Count'] || 0}` },
        { key: 4, label: `待发货 ${this.tabList['pendingSend_Count'] || 0}` },
        { key: 5, label: `待收货 ${this.tabList['pendingSign_Count'] || 0}` },
        { key: 6, label: `待评价 ${this.tabList['pendingReplyd_Count'] || 0}` },
        { key: 7, label: `已退款 ${this.tabList['refund_Count']}` },
        { key: 8, label: `交易完成 ${this.tabList['completed_Count'] || 0}` },
        { key: 9, label: `已删除 ${this.tabList['del_Count'] || 0}` }
      ])
      this.$set(this.list, 'cartLists', [
        {
          outerBack: '#e4ecff',
          InnerBack: '#4d7cfe',
          icon: 'el-icon-s-order',
          num: val['successful_Count'],
          title: '订单数量'
        },
        {
          outerBack: '#fff3e0',
          InnerBack: '#ffab2b',
          icon: 'el-icon-edit',
          num: NumFormat(val['successful_Price']),
          title: '订单金额'
        },
        {
          outerBack: '#eaf9e1',
          InnerBack: '#6dd230',
          icon: 'el-icon-s-comment',
          num: val['today_Successful_Count'],
          title: '今日订单数量'
        },
        {
          outerBack: '#ffeaf4',
          InnerBack: '#ff85c0',
          icon: 'el-icon-s-finance',
          num: NumFormat(val['today_Successful_Price']),
          title: '今日支付金额'
        }
      ])
    }
  },
  methods: {
    ...mapActions({
      tableFromMode: 'order/setOrderTableFromMode',
      tableFromStatus: 'order/setOrderTableFromStatus',
      setOrderPageCurrentPage: 'order/setOrderPageCurrentPage',
      tableFromDateLimit: 'order/setOrderTableFromDateLimit',
      tableFromKeywords: 'order/setOrderTableFromKeywords',
      tableFromIsDel: 'order/setOrderTableFromIsDel',
      getOredrList: 'order/getList'
    }),
    onSeachKeywordList() {
      this.setOrderPageCurrentPage(1)
      this.getOredrList()
    },
    onStatus() {
      this.setOrderPageCurrentPage(1)
      this.getOredrList()
    },
    onPaymentMethod() {
      this.setOrderPageCurrentPage(1)
      this.getOredrList()
    },
    choice(val, key) {
      if (key === 'payType') {
        const data = {
          0: '微信支付',
          1: '支付宝支付'
        }
        return data[val]
      } else if (key === 'state') {
        const data = {
          0: '订单已生成',
          1: '未支付',
          2: '已取消',
          3: '订单取消',
          4: '待发货',
          5: '待收货',
          6: '待评价',
          7: '已退款',
          8: '交易完成',
          21: '待退款'
        }
        return data[val]
      } else if (key === 'payChannel') {
        const data = {
          0: '微信公众号',
          1: '小程序'
        }
        return data[val]
      } else if (key === 'gender') {
        const data = {
          0: '男',
          1: '女',
          2: '未知'
        }
        return data[val]
      } else if (key === 'isDel') {
        const data = {
          0: '未删除',
          1: '已删除'
        }
        return data[val]
      }
    },
    async onInvoiceExports() {
      if (this.totalCount === 0) return

      const list = this.selectionDate.length > 0 ? { data: this.selectionDate } : await getOrderList({ PageNumber: 1, PageSize: 30 })
      const tHeader = ['ID', '订单号', '物流公司', '物流编码', '物流单号', '用户信息', '手机号', '商品信息']
      const filterVal = ['id', 'orderNo', 'deliveryName', 'deliveryCode', 'deliveryNum', 'info', 'consigneeMobile', 'title']
      const data = this.invoiceFormatJson(filterVal, list.data.map((item, index) => {
        return {
          id: this.selectionDate.length > 0 ? item.orderId : item.id,
          orderNo: item.orderNo,
          deliveryName: item.deliveryName,
          deliveryCode: item.deliveryCode,
          deliveryNum: item.deliveryNum,
          info: this.selectionDate.length > 0 ? {
            nickName: item.info.nickName,
            realName: item.info.realName,
            mobile: item.info.mobile,
            gender: item.info.gender,
            address: item.info.address
          } : {
            nickName: item.user.nickName,
            realName: item.user.realName,
            mobile: item.user.mobile,
            gender: item.user.gender,
            address: item.user.address
          },
          consigneeMobile: item.consigneeMobile,
          title: this.selectionDate.length > 0 ? item.title : item.orderItems.map((order) => {
            return order.productAttrValue.product.title
          })
        }
      }))

      import('@/vendor/Export2Excel').then(async excel => {
        excel.export_json_to_excel({
          header: tHeader,
          data: data,
          filename: `导出发货单_${new Date().getTime()}`,
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    async onExports() {
      if (this.totalCount === 0) return
      import('@/vendor/Export2Excel').then(async excel => {
        const list = this.selectionDate.length > 0 ? { data: this.selectionDate } : await getOrderList({ PageNumber: 1, PageSize: 30 })
        const tHeader = ['ID', '订单号', '收货人姓名', '收货人电话', '收货地址', '商品信息', '总价格', '实际支付', '邮费', '支付方式', '支付时间', '支付渠道', '订单状态', '创建时间', '删除状态', '管理员备注']
        const filterVal = ['id', 'orderNo', 'consigneeName', 'consigneeMobile', 'consigneeAddress', 'title', 'totalPrice', 'payPrice', 'totalPostage', 'payType', 'payDateUTC', 'payChannel', 'state', 'createDateUTC', 'isDel', 'remark']
        const data = this.formatJson(filterVal, list.data.map((item, index) => {
          const obj = {
            id: this.selectionDate.length > 0 ? item.orderId : item.id,
            orderNo: item.orderNo,
            consigneeName: item.consigneeName,
            consigneeMobile: item.consigneeMobile,
            consigneeAddress: item.consigneeAddress,
            title: this.selectionDate.length > 0 ? item.title : item.orderItems.map((order) => {
              return order.productAttrValue.product.title
            }),
            totalPrice: this.selectionDate.length > 0 ? NumFormat(item.children.totalPrice) : NumFormat(item.totalPrice),
            payPrice: NumFormat(item.payPrice),
            totalPostage: this.selectionDate.length > 0 ? NumFormat(item.children.totalPrice) : NumFormat(item.totalPostage),
            payType: this.choice(item.payType, 'payType'),
            payDateUTC: this.$moment.utc(item.payDateUTC).tz(this.$moment.tz.guess()).format('YYYY-MM-DD HH:mm:ss'),
            payChannel: this.choice(item.payChannel, 'payChannel'),
            state: this.choice(item.state, 'state'),
            createDateUTC: this.$moment.utc(this.selectionDate.length > 0 ? item.children.totalPrice : item.createDateUTC).tz(this.$moment.tz.guess()).format('YYYY-MM-DD HH:mm:ss'),
            isDel: this.choice(item.isDel, 'isDel'),
            remark: item.remark
          }
          // item.isDel ? obj.isDel = 1 : ''
          return obj
        }))

        excel.export_json_to_excel({
          header: tHeader,
          data: data,
          filename: `订单导出_${new Date().getTime()}`,
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    invoiceFormatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'info') {
          return `昵称：${v[j].nickName}    真实姓名：${v[j].realName}    手机号：${v[j].mobile}    性别：${this.choice(v[j].gender, 'gender')}    地址：${v[j].address}`
        } else {
          return v[j]
        }
      }))
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
